# -*- conding:utf-8 -*-
# coding=utf-8
import serial
import time
import json
import threading
from time import ctime, sleep
import queue

q = queue.Queue()
# ser = serial.Serial("/dev/ttyUSB0",115200)
ser = serial.Serial("COM4", 115200, timeout=5)


def Zigbee():
    while True:
        count = ser.inWaiting()
        if count != 0:
            recv = ser.readline()
            ser.flushInput()  # 缓冲区
            q.put(recv.decode())
            data = recv.decode('utf-8')
            print(recv.decode())
        sleep(0.1)


def Zigbee_json():
    global recv
    while True:
        if q.empty():  # 如果队列为空，返回True,反之。。
            pass
        else:
            data = q.get('gbk')  # 获取队列
            tmp_output = open('E:/savedata/wendu.txt', 'w')
            tmp_output.write(data)
            tmp_output.flush()
            tmp_output.close()
            print(data)
            sleep(1)


threads = []
t1 = threading.Thread(target=Zigbee)
threads.append(t1)
t2 = threading.Thread(target=Zigbee_json)
threads.append(t2)
if __name__ == '__main__':
    for t in threads:
        t.start()
    t1.join()
    t2.join()
    while True:
        sleep(2)